package com.xd.oauth.config;

import cn.hutool.json.JSONUtil;
import com.xd.user.api.entity.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Map;

/**
 * @author huboxin
 * @title: JwtAccessToken
 * @projectName bk
 * @description:  装配jwt内容
 * @date 2019/12/3114:50
 */
public class JwtAccessToken extends JwtAccessTokenConverter {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        DefaultOAuth2AccessToken oAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken);
        User user=null;
        try{
            user= (User) authentication.getPrincipal();
        }catch (Exception e){
            return super.enhance(accessToken, authentication);
        }
        user.setPassword("");
        user.setPermissions(null);
        oAuth2AccessToken.getAdditionalInformation().put("user",JSONUtil.toJsonStr(user));
        return super.enhance(oAuth2AccessToken, authentication);
    }


    /**
     * 解析token
     * @param value
     * @param map
     * @return
     */
    @Override
    public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map){
        OAuth2AccessToken oauth2AccessToken = super.extractAccessToken(value, map);
        convertData(oauth2AccessToken, oauth2AccessToken.getAdditionalInformation());
        return oauth2AccessToken;
    }

    private void convertData(OAuth2AccessToken accessToken,  Map<String, ?> map) {
        accessToken.getAdditionalInformation().put("user",convertUserData(map.get("user")));
    }

    private User convertUserData(Object map) {
        String json = JSONUtil.toJsonStr(map);
        return JSONUtil.toBean(json, User.class);
    }
}
